package com.example.wac.component;

import cn.hutool.json.JSONUtil;
import com.example.wac.enums.WeChatUrlEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wuancheng
 * @description
 * @date 2022-07-25 17:26:00
 */

@Slf4j
@Component
public class HttpHelper {
    @Autowired
    RestTemplate restTemplate;

    private static HttpHeaders httpHeaders;

    static {
        httpHeaders = new HttpHeaders();
        httpHeaders.add( "Accept", "application/json");
    }

    public Map<String, Object> postForObject(Map paramUrlMap, Map paramMap, WeChatUrlEnum weChatUrlEnum){
        HttpEntity<String> fromEntity = new HttpEntity<>(JSONUtil.toJsonStr(paramMap), httpHeaders);
        try {
            String url = replaceUrlParam(weChatUrlEnum.urlValue(), paramUrlMap);
            log.info("请求微信服务端url:{},请求参数param:{}", url, paramMap);
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, fromEntity, Map.class);
            Map resultMap = responseEntity.getBody();
            log.info("请求微信服务端url:{},响应体:{}", url, resultMap);
            return resultMap;
        }catch (Exception e){
            log.error("调用微信服务失败", e);
        }
        return null;
    }

    public Map<String, Object> getForObject(Map paramMap, WeChatUrlEnum weChatUrlEnum){
        HttpEntity<String> fromEntity = new HttpEntity<>(httpHeaders);
        try {
            String url = replaceUrlParam(weChatUrlEnum.urlValue(), paramMap);
            log.info("请求微信服务端url:{},请求参数param:{}", url, paramMap);
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.GET, fromEntity, Map.class);
            Map resultMap = responseEntity.getBody();
            log.info("请求微信服务端url:{},响应体:{}", url, resultMap);
            return resultMap;
        }catch (Exception e){
            log.error("调用微信服务失败");
        }
        return null;
    }

    /**
     * 解析替换url中的变量
     *
     * @param url
     * @param paramMap
     * @return
     */
    private String replaceUrlParam(String url, Map paramMap){
        if (!url.contains("{") || MapUtils.isEmpty(paramMap)){
            return url;
        }
        Set<String> keySet = (Set<String>) paramMap.keySet().stream().collect(Collectors.toSet());
        String paramKey;
        for (String key : keySet) {
            paramKey = "{" + key + "}";
            if (url.contains(paramKey)){
              url = url.replace(paramKey, (String) paramMap.get(key));
            }
        }
        return url;
    }

}
